<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Core_UserController extends Zend_Controller_Action
{
    private $_userService;
    private $_memberService;
    private $_emailService;
    private $_nextOfKinService;
    private $_diplomaService;

    public function init()
    {
        $this->_userService = $this->_helper->getService('Core_Service_User');
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
        $this->_emailService = $this->_helper->getService('Core_Service_Email');
        $this->_nextOfKinService = $this->_helper->getService('Core_Service_NextOfKin');
        $this->_diplomaService = $this->_helper->getService('Core_Service_Diploma');
    }

    public function removeDiplomaAction()
    {
        $diplomaId = $this->_getParam('id');

        $validator = new Zend_Validate_Int();
        if (!$validator->isValid($diplomaId)) {
            throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt for slettinga av sertifikat');
        }

        $diplomaId = (int)$diplomaId;
        $diploma = $this->_diplomaService->fetch($diplomaId);

        if (!$diploma instanceof Core_Model_Diploma) {
            throw new RedCross_Exception_NotFound('Sertifikat med id ' . $diplomaId . ' ikke funnet.');
        }

        $success = $diploma->delete();

        if ($success) {
            $this->view->flashMessage()->addMessage('Sertifikat fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
        } else {
            $this->view->flashMessage()->addMessage('Feil oppstod. Sertifikat ikke slettet.');
        }

        return $this->_helper->redirector('edit');
    }

    public function removeNextOfKinAction()
      {
          $nextOfKinId = $this->_getParam('id');

          $validator = new Zend_Validate_Int();
          if (!$validator->isValid($nextOfKinId)) {
              throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt for sletting av pårørende: '$nextOfKinId'");
          }

          $nextOfKinId = (int)$nextOfKinId;

          $nextOfKinService = $this->_helper->getService('Core_Service_NextOfKin');
          $nextOfKin = $nextOfKinService->fetch($nextOfKinId);

          if (!$nextOfKin instanceof Core_Model_NextOfKin) {
              throw new RedCross_Exception_NotFound('Pårørende med id ' . $nextOfKinId . ' ikke funnet');
          }
          $memberId = $nextOfKin->member_id;
          $authService = $this->_helper->authenticator();
          $success = $nextOfKinService->delete($nextOfKin, $authService);

          if ($success) {
              $this->view->flashMessage()->addMessage('Pårørende fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
          } else {
              $this->view->flashMessage()->addMessage('Feil oppstod. Pårørende ikke slettet.');
          }

          return $this->_helper->redirector('edit');
      }

    public function createAction()
    {
        $this->_helper->acl()->isAllowed('service:user', 'create');

        $form = new Core_Form_User_Register();
        $this->view->form = $form;

        $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
            $user = $this->_userService->create($form->getValues());
            if ($user) {
                return $this->_forward('registration-complete', null, null, $form->getValues());
            }
        }
    }

    public function registrationCompleteAction()
    {
        // Form-values fra createAction blir forwardet hit, så de kan bli hentet ved å kalle metoden under
        $this->view->username = $this->_getParam('username');
    }

    public function loginAction()
    {
        /*
        $isActive = Core_Model_Member::isActive();
        if ($isActive) {
            return $this->_helper->redirector('profile');
        }
         */ 
        if ($this->_helper->authenticator()->isAuthenticated()) {
            //return $this->_helper->redirector('profile');
            return $this->_helper->redirector('index', 'index');
        }

        $this->view->form = $this->_helper->authenticator()->getLoginForm();

        $request = $this->getRequest();
        if ($request->isPost() && $this->view->form->isValid($request->getPost())) {
            $authenticated = $this->_helper->authenticator()->login($this->view->form->getValues());
            if ($authenticated) {
                //return $this->_helper->redirector('profile');
                return $this->_helper->redirector('index', 'index');
            }
        }
    }

    public function logoutAction()
    {
        if ($this->_helper->authenticator()->isAuthenticated()) {
            $this->_helper->authenticator()->logout();
        }
        return $this->_helper->redirector('index', 'index');
    }

    public function lostPasswordAction()
    {
        $form = new Core_Form_User_LostPassword();
        $this->view->form = $form;

        $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
            $service = $this->_helper->getService('Core_Service_PasswordReset');
            $resetRequest = $service->createRequest($form->getValues());
            $this->view->result = $resetRequest;
        }
    }

    public function resetPasswordAction()
    {
        $userId = $this->_getParam('id', null);
        $resetKey = $this->_getParam('key', null);

        $intValidator = new Zend_Validate_Int();
        $sha1Validator = new Zend_Validate_Regex('/^[0-9a-fA-F]{40}$/');
        if (!$intValidator->isValid($userId) || !$sha1Validator->isValid($resetKey)) {
            throw new RedCross_Exception_ValidationFailed();
        }
        $userId = (int) $userId;

        // Check if a request with that user id and reset key exists
        $resetService = $this->_helper->getService('Core_Service_PasswordReset');
        $resetRequest = $resetService->fetchRequest($userId, $resetKey);
        if (!$resetRequest) {
            $this->view->invalid = true;
          return;
        } else if ($resetRequest->isExpired()) {
            $this->view->expired = true;
          return;
        }

        $form = new Core_Form_User_ChangePassword();
        $this->view->form = $form;

        $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
          $user = $this->_userService->changePassword($userId, $form->getValue('password'));
            $resetService->deleteRequests($userId);
          return $this->_helper->redirector('login');
        }
    }

    public function viewAction()
    {
      $authService = $this->_helper->authenticator();
      if (!$authService->isAuthenticated()) {
        // User is not authenticated. Display login page.
        return $this->_helper->redirector('login');
      }

    $userId = $this->_getParam('id', false);
      $this->isAdmin = false;

        $validator = new Zend_Validate_Int();
        if ($userId && !$validator->isValid($userId)) {
            throw new RedCross_Exception_ValidationFailed();
        } else if ($userId && $validator->isValid($userId)) {
            // Check ACL if allowed to view all users
            $this->_helper->acl()->isAllowed('service:user', 'viewAll');
            $this->view->isAdmin = $this->_helper->acl()->isAllowed('service:user', 'viewAll');
            $this->view->userId = $userId;
        } else {
            $userId = $authService->getIdentity()->id;
        }
        $userId = (int) $userId;

        $user = $this->_userService->fetchByIdForProfile($userId);
        if (!$user) {
            throw new RedCross_Exception_NotFound();
        }
        $this->view->user = $user;

        $memberService = $this->_helper->getService('Core_Service_Member');
        $this->view->member = $user->Member;

        $this->view->isPermanentPassive = $memberService->isPermanentPassive($user->Member->id);

        $shiftService = $this->_helper->getService('Core_Service_Shift');
        $this->view->futureShifts = $shiftService->fetchFutureShifts(0, 5, $user->Member->id);
        $this->view->pastShifts = $shiftService->fetchPastShifts(0, null, $user->Member->id);

        $this->view->diplomas = $this->_diplomaService->fetchAllForMemberId($user->Member->id);

        $courseService = $this->_helper->getService('Core_Service_Course');
        $courses = $courseService->fetchAllCoursesForMember($user->Member->id);
        $this->view->courses = $courses;
        $competences = $courseService->fetchAllCompetencesForMember($user->Member->id);
        $this->view->competences = $competences;

        $interestService = $this->_helper->getService('Core_Service_Interest');
        $interests = $interestService->fetchAllInterestsForMember($user->Member->id);
        $this->view->interests = $interests;

        $passiveService = $this->_helper->getService('Core_Service_Passive');
        $passiveMessages = $passiveService->fetchPassiveMessagesForMember($user->Member->id, 0, null);
        $this->view->passiveMessages = $passiveMessages;
    }

  public function changePasswordAction()
  {
        $authService = $this->_helper->authenticator();
        if (!$authService->isAuthenticated()) {
        // User is not authenticated. Display login page.
        return $this->_helper->redirector('login');
      }

    $form = new Core_Form_User_ChangePassword();
    $this->view->form = $form;

    $request = $this->getRequest();
        if ($request->isPost() && $form->isValid($request->getPost())) {
          $user = $this->_userService->fetchById($authService->getIdentity()->id);
          $this->view->user = $user;

          $this->_userService->changePassword($user->id, $form->getValue('password'));

          $this->view->flashMessage()->addMessage('Passordendringen var vellykket.', RedCross_View_Helper_FlashMessage::SUCCESS);
          return $this->_helper->redirector('profile');
        }
  }

  public function editAction()
  {
      $memberId = $this->_getParam('id');

      $privacyForm = new Core_Form_User_Privacy();
      $personalInfoForm = new Core_Form_User_Edit();
      $phoneInfoForm = new Core_Form_User_Phone();
      $emailInfoForm = new Core_Form_User_Email();
      $nextOfKinInfoForm = new Core_Form_User_NextOfKin();
      $uploadDiplomaForm = new Core_Form_User_UploadDiploma();

      $authService = $this->_helper->authenticator();
      $user = $this->_userService->fetchById($authService->getIdentity()->id);
      $this->view->user = $user;

      $memberService = $this->_helper->getService('Core_Service_Member');
      $member = $memberService->fetchWithPhoneAndEmail($user['Member']['id']);
      $this->view->member = $member;
      $privacyForm->fillForm($member);
      $personalInfoForm->fillForm($member);
      $memberId = $authService->getIdentity()->member_id;

      $flashMessenger = $this->view->flashMessage();
      $request = $this->getRequest();

      if($request->isPost()){
      $params = $request->getParams();
      $params['id'] = $memberId;

      // Opdatering a bruker fra form (når bruker redigerer sin egen profil)
      if(isset($params['submit_personalia']) && $personalInfoForm->isValid($params)){
        $member = $this->_memberService->fetch((int)$memberId);
        $member->address = $params['address'];
        $member->address_2 = $params['address_2'];
        $member->postal_id = $params['postal_code'];
        $result = $this->_memberService->save($member);
        $this->view->personaliaMessage = $result ?
          $flashMessenger->renderMessage('Oppdateringen utført', RedCross_View_Helper_FlashMessage::SUCCESS) :
          $flashMessenger->renderMessage('Det oppstod en feil. Last siden på nytt og prøv igen.', RedCross_View_Helper_FlashMessage::ERROR);
      }

      // Oppdatering av privacy, tilgjenglighet av informasjon
      if(isset($params['submit_privacy']) && $privacyForm->isValid($params)){
        $member = $this->_memberService->fetch((int)$memberId);
        $member->is_public = $params['is_public'];
        $result = $this->_memberService->save($member);
        $this->view->personaliaMessage = $result ?
          $flashMessenger->renderMessage('Oppdateringen utført', RedCross_View_Helper_FlashMessage::SUCCESS) :
          $flashMessenger->renderMessage('Det oppstod en feil. Last siden på nytt og prøv igen.', RedCross_View_Helper_FlashMessage::ERROR);
      }

    // Legge til telefonnummer
    if(isset($params['submit_phone']) && $phoneInfoForm->isValid($params)) {
        $result = $this->_memberService->addPhone($memberId, $phoneInfoForm->getValues());
        if ($result === Core_Service_Member::PHONE_DUPLICATE) {
      $this->view->phoneMessage = $flashMessenger->renderMessage('Telefonnummer allerede registrert', RedCross_View_Helper_FlashMessage::ERROR);
        } else if (!$result) {
      $this->view->phoneMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
        } else {
                    $member = $this->_memberService->fetchWithPhoneAndEmail($memberId);
                    $this->view->phoneMessage = $flashMessenger->renderMessage('Telefonnummer lagt til', RedCross_View_Helper_FlashMessage::SUCCESS);
                    $phoneInfoForm->reset();
        }
    }

    // Legge til epost
    if(isset($params['submit_email']) && $emailInfoForm->isValid($params)){
         $result = $this->_memberService->addEmail($memberId, $params/*$emailInfoForm->getValues()*/);
        if ($result === Core_Service_Member::EMAIL_DUPLICATE) {
      $this->view->emailMessage = $flashMessenger->renderMessage('Denne epost-adressen er allerede registrert i systemet', RedCross_View_Helper_FlashMessage::ERROR);
        } else if (!$result) {
      $this->view->emailMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført', RedCross_View_Helper_FlashMessage::ERROR);
        } else {
                    $this->view->emailMessage = $flashMessenger->renderMessage('Epost-adressen er lagt til', RedCross_View_Helper_FlashMessage::SUCCESS);
                    $emailInfoForm->reset();
                }
        }
      }

      //Legge til pårørende
      if (isset($params['submit_nextofkin']) && $nextOfKinInfoForm->isValid($params)) {
          $result = $this->_memberService->addNextOfKin($memberId, $params);
          if (!$result) {
              $this->view->nextOfKinMessage = $flashMessenger->renderMessage('En feil oppstod. Oppdatering ikke utført.', RedCross_View_Helper_FlashMesage::ERROR);
          } else {
              $this->view->nextOfKinMessage = $flashMessenger->renderMessage('Pårørende lagt til.', RedCross_View_Helper_FlashMessage::SUCCESS);
              $nextOfKinInfoForm->reset();
          }
      }

      //Laste opp diploma
      if (isset($params['submit_diploma']) && $uploadDiplomaForm->isValid($params)) {
          try {
            $uploadedData = $uploadDiplomaForm->getValues();
            $fullFilePath = $uploadDiplomaForm->file->getFileName();

            // figuring out new file name
            preg_match('/.*(\.\w+)$/i', $fullFilePath, $matches);
            $fileExtension = $matches[1];
            $newFileName = time() . '-member-' . $memberId . $fileExtension;
            $newFilePath = Zend_Registry::get('upload_final_path') . $newFileName;

            // move file to its permanent location
            rename($fullFilePath, $newFilePath);

            // add record in db
            $values = $uploadDiplomaForm->getValues();
            $this->_diplomaService->create($values['description'], $newFileName, $memberId);
          } catch (Zend_File_Transfer_Exception $e) {
              $e->getMessage();
          }
      }

      $this->view->privacyForm = $privacyForm;
      $this->view->personalInfoForm = $personalInfoForm;
      $this->view->phoneInfoForm = $phoneInfoForm;
      $this->view->emailInfoForm = $emailInfoForm;
      $this->view->nextOfKinInfoForm = $nextOfKinInfoForm;
      $this->view->uploadDiplomaForm = $uploadDiplomaForm;
  }

  public function removePhoneAction()
  {
      $this->_helper->viewRenderer->setNoRender(true);
      $phoneId = $this->_getParam('id');

      $validator = new Zend_Validate_Int();
      if (!$validator->isValid($phoneId)) {
          throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt for sletting av telefon: '$phoneId'");
      }
      $phoneId = (int)$phoneId;

      $phoneService = $this->_helper->getService('Core_Service_Phone');
      $phone = $phoneService->fetch($phoneId);
      if (!$phone instanceof Core_Model_Phone) {
          throw new RedCross_Exception_NotFound('Telefonnummer med id ' . $phoneId . ' ikke funnet');
      }
      $memberId = $phone->member_id;
      $success = $phoneService->delete($phone);

      if($success) {
    $this->view->flashMessage()->addMessage('Telefonnummer fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
      } else {
    $this->view->flashMessage()->addMessage('Minst ett telefonnummer må være registrert', RedCross_View_Helper_FlashMessage::ERROR);
      }
      return $this->_helper->redirector('edit');
  }

  public function removeEmailAction()
  {
      $this->_helper->viewRenderer->setNoRender(true);
      $emailId = $this->_getParam('id');

      $validator = new Zend_Validate_Int();
      if (!$validator->isValid($emailId)) {
    throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt for sletting av epostadresse: '$emailId'");
      }
      $emailId = (int)$emailId;
      $email = $this->_emailService->fetch($emailId);
      if (!is_object($email)) {
          throw new RedCross_Exception_NotFound('Epostadresse med id ' . $emailId . ' ikke funnet');
      }

      $memberId = $email->member_id;
      $success = $this->_emailService->delete($email);

      if($success === Core_Service_Email::EMAIL_DELETE_ERROR_IS_MAIN) {
          $this->view->flashMessage()->addMessage('En hovedepostadresse kan ikke slettes', RedCross_View_Helper_FlashMessage::ERROR);
      } else if($success === Core_Service_Email::EMAIL_DELETE_ERROR_IS_ONLY) {
          $this->view->flashMessage()->addMessage('Minst en epostadresse må være registrert', RedCross_View_Helper_FlashMessage::ERROR);
      } else if($success === true) {
          $this->view->flashMessage()->addMessage('Epostadresse fjernet', RedCross_View_Helper_FlashMessage::SUCCESS);
      } else {
          $this->view->flashMessage()->addMessage('En ukjent feil oppstod under sletting', RedCross_View_Helper_FlashMessage::ERROR);
      }

      return $this->_helper->redirector('edit');
  }

  public function setMainEmailAction()
  {
      $this->_helper->viewRenderer->setNoRender(true);
      $emailId = $this->_getParam('id');
      $validator = new Zend_Validate_Int();
      if (!$validator->isValid($emailId))
      {
    throw new RedCross_Exception_ValidationFailed("Ugyldig parameter angitt. Skal v&aelig;re int");
      }
      $emailId = (int)$emailId;
      $email = $this->_emailService->fetch($emailId);
      if (!is_object($email))
      {
          throw new RedCross_Exception_NotFound('Epostadresse med angitt id ikke funnet');
      }
      $memberId = $email->member_id;
      $success = $this->_emailService->setAsMain($email);
      return $this->_helper->redirector('edit');
  }

  public function applicationAction() {
      $form = new Core_Form_Member_Application();
      $this->view->form = $form;

      $request = $this->getRequest();
      if ($request->isPost() && $form->isValid($request->getPost())) {
        $mail = new RedCross_Mail_Base();
        $receipt = new RedCross_Mail_Base();

        $mail->setSubject('Ny hjelpekorpssøknad ankommet');
        $receipt->setSubject('Din søknad om opptak i Trondheim Røde Kors Hjelpekorps');

        $config = $config = Zend_Registry::get('config');
        $toName = $config['rk']['applicationForm']['recipient']['name'];
        $toAddr = $config['rk']['applicationForm']['recipient']['address'];

        $formValues = $form->getValues();
        $receiptAddr = $formValues['email'];
        $fullName = $formValues['first_name'] . ' ' . $formValues['last_name'];

        $mail->addTo($toAddr, $toName);
        $receipt->addTo($receiptAddr, $fullName);

        $content = new Zend_View();
        $content->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');
        $content->assign('data', $formValues);

        $receiptContent = new Zend_View();
        $receiptContent->setScriptPath(APPLICATION_PATH . '/layouts/main/emails/');
        $receiptContent->assign('data', $formValues);

        $body = $content->render('application.phtml');
        $receiptBody = $content->render('application-receipt.phtml');
        try {
            $mail->setBodyText($body);
            $mail->send();
            $receipt->setBodyText($receiptBody);
            $receipt->send();
            $this->view->flashMessage()->addMessage('Takk! Din søknad har blitt sendt.', RedCross_View_Helper_FlashMessage::SUCCESS);
            $this->_helper->redirector('application');
        } catch (Exception $e) {
            $this->view->flashMessage()->addMessage('Kunne ikke sende epost.', RedCross_View_Helper_FlashMessage::ERROR);
        }
      }
  }

}
